package com.kly.sc.api.application.controller.appsflyer;

import cn.hutool.json.JSONUtil;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.StringUtils;
import com.jsoniter.JsonIterator;
import com.jsoniter.output.JsonStream;
import com.kly.sc.api.application.annos.InitUser;
import com.kly.sc.api.application.annos.SignIgnore;
import com.kly.sc.api.application.annos.VisitorAccessible;
import com.kly.sc.api.application.controller.appsflyer.request.AppFlyerInfoReq;
import com.kly.sc.api.application.helper.RequestLocalInfo;
import com.kly.sc.api.application.service.utils.BaseComponent;
import com.kly.user.dto.StoreAppsflyerUserMappingReq;
import com.kly.user.dto.StoreReportReq;
import com.kly.user.service.AppsflyerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * appsflyer 数据存储
 */
@RestController
@RequestMapping("api/appsflyer")
public class AppFlyerController extends BaseComponent {

    private final Logger logger = LoggerFactory.getLogger(getClass());
    @Resource
    AppsflyerService appsflyerService;


    @ResponseBody
    @RequestMapping(value = "/receive/msg", method = RequestMethod.POST)
    @VisitorAccessible
    @SignIgnore
    public void receiveMsg(@RequestBody(required = false) byte[] body, HttpServletRequest request, HttpServletResponse response) {
        try {
            String paramStr = new String(body, "utf-8");
//            logger.info("====receiveAppsflyerReport==== params :{}", paramStr);

            final StoreReportReq storeReportReq = StoreReportReq.builder().reportContent(paramStr).build();
            appsflyerService.storeAppsFlyerReport(storeReportReq);

//            logger.info("====receiveAppsflyerReportSuccess==== params :{}", paramStr);

        } catch (Exception e) {
            logger.info("====receiveAppsflyerReportFailed====", e);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/addAppFlyerInfo")
    @InitUser
    public Response addAppFlyerInfo(@RequestBody AppFlyerInfoReq appFlyerInfoReq) {
        String request = JsonStream.serialize(appFlyerInfoReq);
        final String userCode = RequestLocalInfo.getCurrentUser().getUserCode();
//        logger.info("====addAppFlyerInfo start====,userCode:{},params:{}", userCode, request);
        String content = null;
        String channel = null;
        String campaign = null;
        String afAdset = null;
        String afAd = null;
        try {
            if (StringUtils.isNotEmpty(appFlyerInfoReq.getChannel())) {
                content = appFlyerInfoReq.getChannel();

                if (StringUtils.isNotEmpty(content) && JSONUtil.isJson(content)) {
                    content = appFlyerInfoReq.getChannel();
                    String af_channel = JsonIterator.deserialize(content).get("af_channel").toString();
                    if (StringUtils.isNotEmpty(af_channel)) {
                        channel = af_channel;
                    } else {
                        channel = JsonIterator.deserialize(content).get("media_source").toString();
                    }
                    campaign = JsonIterator.deserialize(content).get("campaign").toString();
                    afAdset = JsonIterator.deserialize(content).get("af_adset").toString();
                    afAd = JsonIterator.deserialize(content).get("af_ad").toString();
                }else{
                    logger.info("====addAppFlyerInfo 为空1====,userCode:{},params:{}", userCode, request);
                }
            }else{
                logger.info("====addAppFlyerInfo 为空2====,userCode:{},params:{}", userCode, request);
            }
        } catch (Exception e) {
            logger.error("====addAppFlyerInfo error====,userCode:{},params:{}", userCode, request, e);
        }

        StoreAppsflyerUserMappingReq appsFlyerUser = StoreAppsflyerUserMappingReq.builder().userCode(userCode)
                .appflyersId(appFlyerInfoReq.getAppsFlyerUid()).channel(channel).content(appFlyerInfoReq.getChannel())
                .campaign(campaign).afAdset(afAdset).afAd(afAd).build();
        appsflyerService.queryOrStoreIfNotExists(appsFlyerUser);

        return Response.ok();
    }

    @SignIgnore
    @ResponseBody
    @RequestMapping(value = "/modifyAppFlyerInfo")
    public Response modifyAppFlyerInfo(@RequestBody AppFlyerInfoReq appFlyerInfoReq) {
        String request = JsonStream.serialize(appFlyerInfoReq);
        String content = null;
        String channel = null;
        String campaign = null;
        String afAdset = null;
        String afAd = null;
        try {
            if (StringUtils.isNotEmpty(appFlyerInfoReq.getChannel())) {
                content = appFlyerInfoReq.getChannel();
                if (StringUtils.isNotEmpty(content) && JSONUtil.isJson(content)) {
                    content = appFlyerInfoReq.getChannel();
                    String af_channel = JsonIterator.deserialize(content).get("af_channel").toString();
                    if (StringUtils.isNotEmpty(af_channel)) {
                        channel = af_channel;
                    } else {
                        channel = JsonIterator.deserialize(content).get("media_source").toString();
                    }
                    campaign = JsonIterator.deserialize(content).get("campaign").toString();
                    afAdset = JsonIterator.deserialize(content).get("af_adset").toString();
                    afAd = JsonIterator.deserialize(content).get("af_ad").toString();
                }
            }

            StoreAppsflyerUserMappingReq appsFlyerUser = StoreAppsflyerUserMappingReq.builder()
                    .appflyersId(appFlyerInfoReq.getAppsFlyerUid()).channel(channel).content(appFlyerInfoReq.getChannel()).campaign(campaign).afAdset(afAdset).afAd(afAd).build();
            appsflyerService.updateAppflyerInfo(appsFlyerUser);

        } catch (Exception e) {
            logger.error("====addAppFlyerInfo error====,userCode:{},params:{}", request, e);
        }

        return Response.ok();
    }




}
